﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NextHigherNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 15432;

            Next(number);
            Console.Read();
        }

        public static void Next(int number)
        {
            int max = 0;
            Permutation(number.ToString().ToCharArray(), 0,ref max,number);

            Console.WriteLine("Next Higher Number: {0}", max);
            Console.Read();
        }

        private static void Permutation(char[] input, int current, ref int max,  int number)
        {
            if (current == input.Length - 1)
            {
                int temp = int.Parse(new string(input));

                if (temp > number && temp < max)
                {
                    max = temp;
                    //Console.WriteLine("Current number: {0}, Current max: {1}", new string(input), max);
                }
                else if (temp > number && max == 0)
                {
                    max = temp;
                }

                return;                                               
                
            }

            Permutation(input, current + 1,ref max,  number);

            for (int i = current + 1; i < input.Length; i++)
            {
                char temp = input[current];

                input[current] = input[i];
                input[i] = temp;

               Permutation(input, current + 1,ref max,number);
            }

        }
    }


}
